// pages/sale-ticket-judge/sale-ticket-judge-detail.js
const request = require('../../utils/request')
const util = require('../../utils/util')
const dateFormatter = require('../../utils/dateFormatter')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    judgeInfo: {},
    showRefuseDialog: false,
    refuseRemark: '',
    // 倒计时相关
    validHours: 0, // 有效时长(小时)
    remainingTime: '', // 剩余时间显示
    isExpiringSoon: false, // 是否即将过期
    isExpired: false, // 是否已过期
    countdownTimer: null, // 倒计时定时器
    // 预览相关
    showPreview: false,
    previewData: {},
    // 预约单选择相关
    showOrderDialog: false, // 显示预约单选择对话框
    activeOrders: [], // 可选预约单列表
    selectedOrderNos: [] // 选中的预约单编号数组（多选）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const id = options.id
    if (!id) return

    // 先加载配置
    this.loadValidConfig().then(() => {
      // 再加载详情
      this.loadJudgeDetail(id)
    })
  },

  // 加载销售凭证有效时间配置
  loadValidConfig() {
    return request.get('/admin-api/infra/config/get?id=14')
      .then(res => {
        // 默认 3 天
        let days = 3
        if (res && res.code === 0 && res.data && res.data.value) {
          // 后端返回单位为天（字符串），解析为整数，若解析失败仍使用默认值
          days = parseInt(res.data.value, 10) || 3
        }
        const hours = days * 24 // 转换为小时
        this.setData({ validHours: hours })
      })
      .catch(err => {
        console.error('获取配置失败:', err)
        // 请求失败时使用默认值：3天 = 72小时
        this.setData({ validHours: 72 })
      })
  },

  // 加载审核详情
  loadJudgeDetail(id) {
    wx.showLoading({ title: '加载中...' })
    request.get('/admin-api/system/goods-sales-licens/get?id=' + id)
      .then(res => {
        wx.hideLoading()
        if (res.code === 0 && res.data) {
          const data = res.data

          // 状态映射：支持 state (0/1/2) 或 status 字符串
          const s = (data.state != null ? String(data.state) : (data.status || '')).toLowerCase()
          let statusText = '待审核'
          let statusColor = '#FFA000'
          if (s === '1' || s === 'pass' || s === '审核通过') { statusText = '审核通过'; statusColor = '#07C160' }
          if (s === '2' || s === 'refuse' || s === '审核拒绝') { statusText = '审核拒绝'; statusColor = '#F44336' }

          // 优先使用后端提交字段 goodsSalesLicensDetailSaveReqVOS（大小写多变），兼容历史字段
          const details = data.goodsSalesLicensDetailSaveReqVOS || data.GoodsSalesLicensDetailSaveReqVO || data.details || data.list || []

          const judgeInfo = {
            id: data.id,
            merchantId: data.merchantId || data.merchant || '',
            merchantName: data.merchantName || (data.merchant && data.merchant.name) || '',
            customerName: data.customerName || '', // 申请人名称
            submitTime: util.formatYMDHMS(data.createTime) || '',
            auditTime: util.formatYMDHMS(data.okDate) || '',
            // 商户地址和电话（优先从 data 直接获取，兼容从 merchant 对象获取）
            address: data.address || (data.merchant && data.merchant.address) || '',
            phone: data.phone || (data.merchant && data.merchant.phone) || '',
            remark: data.remark || data.note || '',
            refuseRemark: data.refuseRemark || '', // 拒绝原因
            isLicens: !!data.isLicens,
            isCheck: !!data.isCheck,
            state: data.state != null ? data.state : (data.status || 0),
            statusText,
            statusColor,
            createTime: data.createTime, // 保存原始时间戳用于倒计时
            detailsList: details, // 保存原始详情数组（用于提取ID）
            products: (details || []).map(d => ({
              goodsId: d.goodsId || d.id || '', // 商品ID
              name: d.prodName || d.name || d.goodsName || '',
              quantity: d.prodCount || d.quantity || d.count || '',
              origin: d.origin || '',
              certificateUrl: d.certificateUrl || d.certificateUrl || ''
            }))
          }
          
          this.setData({
            judgeInfo
          })

          // 如果不是审核通过状态，启动倒计时
          if (statusText !== '审核通过' && data.createTime) {
            this.startCountdown(data.createTime)
          }
        } else {
          wx.showToast({ title: '未找到数据', icon: 'none' })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('获取审核详情失败', err)
        wx.showToast({ title: '加载失败', icon: 'none' })
      })
  },

  navigateBack() {
    // 清除定时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer)
    }
    wx.navigateBack()
  },

  // 启动倒计时
  startCountdown(createTime) {
    if (!createTime || !this.data.validHours) return

    const updateCountdown = () => {
      const now = Date.now()
      const createTimestamp = new Date(createTime).getTime()
      const validMilliseconds = this.data.validHours * 60 * 60 * 1000
      const expireTime = createTimestamp + validMilliseconds
      const remaining = expireTime - now

      if (remaining <= 0) {
        // 已过期
        this.setData({
          remainingTime: '已过期',
          isExpiringSoon: true,
          isExpired: true
        })
        if (this.data.countdownTimer) {
          clearInterval(this.data.countdownTimer)
        }
        return
      }

      // 计算剩余时间
      const days = Math.floor(remaining / (1000 * 60 * 60 * 24))
      const hours = Math.floor((remaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((remaining % (1000 * 60)) / 1000)

      // 格式化显示
      let remainingTime = ''
      if (days > 0) {
        remainingTime = `${days}天${hours}小时${minutes}分${seconds}秒`
      } else if (hours > 0) {
        remainingTime = `${hours}小时${minutes}分${seconds}秒`
      } else {
        remainingTime = `${minutes}分${seconds}秒`
      }

      // 少于12小时视为即将过期
      const totalHours = days * 24 + hours
      const isExpiringSoon = totalHours < 12

      this.setData({
        remainingTime,
        isExpiringSoon,
        isExpired: false
      })
    }

    // 立即执行一次
    updateCountdown()

    // 每秒更新
    const timer = setInterval(updateCountdown, 1000)
    this.setData({ countdownTimer: timer })
  },

  // 审核通过
  approveApplication() {
    const id = this.data.judgeInfo && this.data.judgeInfo.id
    if (!id) {
      wx.showToast({ title: '缺少申请单ID', icon: 'none' })
      return
    }

    // 检查是否已过期，过期需要二次确认
    if (this.data.isExpired) {
      wx.showModal({
        title: '销售凭证已过期',
        content: '该销售凭证已超过有效期，是否继续审核通过？',
        confirmText: '继续通过',
        confirmColor: '#07C160',
        success: (modalRes) => {
          if (modalRes.confirm) {
            // 加载预约单列表
            this.loadActiveOrders()
          }
        }
      })
      return
    }

    // 未过期，直接加载预约单列表
    this.loadActiveOrders()
  },

  // 加载可选预约单列表
  loadActiveOrders() {
    const createTime = this.data.judgeInfo.createTime
    const merchantId = this.data.judgeInfo.merchantId
    const detailsList = this.data.judgeInfo.detailsList || []
    
    if (!createTime) {
      wx.showToast({ title: '缺少申请时间', icon: 'none' })
      return
    }

    if (!merchantId) {
      wx.showToast({ title: '缺少商户ID', icon: 'none' })
      return
    }

    // 从 goodsSalesLicensDetailSaveReqVOS 中提取 id 并用逗号拼接
    const goodsId = detailsList
      .map(d => d.goodsId)
      .filter(id => id) // 过滤掉空值
      .join(',')

    // 格式化时间为 "年月日 时分秒" 格式 (YYYY-MM-DD HH:mm:ss)
    const formattedTime = dateFormatter.formatToStandardDateTime(createTime)

    const params = { 
      time: formattedTime,
      merchantId: merchantId
    }
    
    // 如果有商品ID，添加到参数中
    if (goodsId) {
      params.goodIds = goodsId
    }

    // 获取当前系统登录的商户ID，用于判断是否场内调货
    const currentMerchantId = wx.getStorageSync('merchantId') || ''

    wx.showLoading({ title: '加载预约单...' })
    request.get('/admin-api/system/order-apply/activeOrder', params)
      .then(res => {
        wx.hideLoading()
        if (res.code === 0 && res.data) {
          const orders = Array.isArray(res.data) ? res.data : (res.data.list || [])
          // 为每个订单添加 selected 属性，并规范化到达时间的页面显示字段
          // 同时检查 aboutMerchant 是否包含当前商户ID，标记为场内调货
          const ordersWithSelected = orders.map(order => {
            const arriveRaw = order.arriveDate || order.planArriveDate || order.arriveTime || ''
            const displayArrive = arriveRaw ? dateFormatter.formatDateYMD(arriveRaw) : ''
            
            // 检查 aboutMerchant 是否包含当前商户ID
            let isInternalTransfer = false
            if (currentMerchantId && order.aboutMerchant) {
              // aboutMerchant 可能是逗号分隔的字符串或数组
              const aboutMerchantStr = String(order.aboutMerchant)
              const aboutMerchantList = aboutMerchantStr.split(/[,，]/).map(id => id.trim())
              isInternalTransfer = aboutMerchantList.includes(String(currentMerchantId))
            }
            
            return {
              ...order,
              selected: false,
              displayArriveDate: displayArrive,
              isInternalTransfer: isInternalTransfer
            }
          })
          this.setData({
            activeOrders: ordersWithSelected,
            selectedOrderNos: [], // 重置为空数组
            showOrderDialog: true
          })
        } else {
          wx.showToast({ title: '加载预约单失败', icon: 'none' })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('加载预约单失败:', err)
        wx.showToast({ title: '加载预约单失败', icon: 'none' })
      })
  },

  // 选择/取消选择预约单（多选）
  selectOrder(e) {
    const orderNo = e.currentTarget.dataset.orderno
    const activeOrders = this.data.activeOrders
    const selectedOrderNos = [...this.data.selectedOrderNos]
    
    // 找到点击的订单索引
    const orderIndex = activeOrders.findIndex(order => order.orderNo === orderNo)
    if (orderIndex === -1) {
      console.error('未找到订单:', orderNo)
      return
    }
    
    // 获取当前选中状态并切换
    const currentSelected = activeOrders[orderIndex].selected || false
    const newSelected = !currentSelected
    
    console.log('点击订单:', orderNo, '原状态:', currentSelected, '新状态:', newSelected)
    
    // 使用路径方式更新选中状态（确保视图更新）
    this.setData({
      [`activeOrders[${orderIndex}].selected`]: newSelected
    })
    
    // 更新选中的订单编号数组
    if (newSelected) {
      // 添加到选中列表
      if (!selectedOrderNos.includes(orderNo)) {
        selectedOrderNos.push(orderNo)
      }
    } else {
      // 从选中列表移除
      const index = selectedOrderNos.indexOf(orderNo)
      if (index > -1) {
        selectedOrderNos.splice(index, 1)
      }
    }
    
    // 更新选中列表
    this.setData({ 
      selectedOrderNos: selectedOrderNos
    })
    
    console.log('当前已选中:', selectedOrderNos)
  },

  // 隐藏预约单选择对话框
  hideOrderDialog() {
    this.setData({
      showOrderDialog: false,
      selectedOrderNos: []
    })
  },

  // 确认选择预约单并执行审核
  confirmOrderSelection() {
    const { selectedOrderNos } = this.data
    if (selectedOrderNos.length === 0) {
      wx.showToast({ title: '请至少选择一个预约单', icon: 'none' })
      return
    }

    // 将选中的订单编号用逗号拼接
    const aboutOrder = selectedOrderNos.join(',')
    
    this.setData({ showOrderDialog: false })
    this.executeApprove(this.data.judgeInfo.id, aboutOrder)
  },

  // 执行审核通过操作
  executeApprove(id, aboutOrder) {
    wx.showLoading({ title: '处理中...' })
    const params = { id: id }
    if (aboutOrder) {
      params.aboutOrder = aboutOrder
    }
    
    request.put('/admin-api/system/goods-sales-licens/updateOK', params)
      .then(resp => {
        wx.hideLoading()
        if (resp.code === 0) {
          wx.showToast({ title: '审核通过', icon: 'success' })
          // 触发上一页刷新
          try {
            const pages = getCurrentPages()
            if (pages && pages.length >= 2) {
              const prev = pages[pages.length - 2]
              if (prev && typeof prev.loadApplications === 'function') {
                prev.setData({ pageNo: 1 })
                prev.loadApplications(false).catch(() => {})
              }
            }
          } catch (e) {
            // ignore
          }
          setTimeout(() => wx.navigateBack(), 800)
        } else {
          wx.showToast({ title: resp.msg || '审核失败', icon: 'none', duration: 2000 })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('审核失败', err)
        wx.showToast({ title: '审核失败', icon: 'none', duration: 2000 })
      })
  },

  // 显示拒绝对话框
  showRefuseDialog() {
    this.setData({
      showRefuseDialog: true,
      refuseRemark: ''
    })
  },

  // 隐藏拒绝对话框
  hideRefuseDialog() {
    this.setData({
      showRefuseDialog: false,
      refuseRemark: ''
    })
  },

  // 阻止点击弹窗内容区域时关闭（空函数即可）
  preventClose() {
    // 阻止事件冒泡到 modal-mask
  },

  // 拒绝原因输入
  onRefuseRemarkInput(e) {
    this.setData({
      refuseRemark: e.detail.value
    })
  },

  // 确认拒绝
  confirmRefuse() {
    const id = this.data.judgeInfo && this.data.judgeInfo.id
    const refuseRemark = this.data.refuseRemark

    if (!id) {
      wx.showToast({ title: '缺少请单ID', icon: 'none' })
      return
    }

    if (!refuseRemark || refuseRemark.trim() === '') {
      wx.showToast({ title: '请填写拒绝原因', icon: 'none' })
      return
    }

    // 检查是否已过期（拒绝时也提醒，但允许操作）
    if (this.data.isExpired) {
      wx.showModal({
        title: '提醒',
        content: '该销售凭证已过期，是否继续拒绝？',
        confirmText: '继续拒绝',
        confirmColor: '#F44336',
        success: (modalRes) => {
          if (modalRes.confirm) {
            this.executeRefuse(id, refuseRemark.trim())
          }
        }
      })
      return
    }

    this.executeRefuse(id, refuseRemark.trim())
  },

  // 执行拒绝操作
  executeRefuse(id, refuseRemark) {
    wx.showLoading({ title: '处理中...' })
    request.put('/admin-api/system/goods-sales-licens/updateRefuse', {
      id: id,
      refuseRemark: refuseRemark
    })
      .then(resp => {
        wx.hideLoading()
        if (resp.code === 0) {
          wx.showToast({ title: '已拒绝', icon: 'success' })
          this.hideRefuseDialog()
          // 触发上一页刷新
          try {
            const pages = getCurrentPages()
            if (pages && pages.length >= 2) {
              const prev = pages[pages.length - 2]
              if (prev && typeof prev.loadApplications === 'function') {
                prev.setData({ pageNo: 1 })
                prev.loadApplications(false).catch(() => {})
              }
            }
          } catch (e) {
            // ignore
          }
          setTimeout(() => wx.navigateBack(), 800)
        } else {
          wx.showToast({ title: resp.msg || '操作失败', icon: 'none' })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('拒绝失败', err)
        wx.showToast({ title: '操作失败', icon: 'none' })
      })
  },

  // 预览凭证
  previewDocument() {
    const judgeInfo = this.data.judgeInfo
    if (!judgeInfo || !judgeInfo.id) return
    
    // 格式化申报时间 (createTime)
    let createYear = '', createMonth = '', createDay = ''
    if (judgeInfo.createTime) {
      const createDateParts = dateFormatter.formatToYearMonthDay(judgeInfo.createTime)
      createYear = createDateParts.year
      createMonth = createDateParts.month
      createDay = createDateParts.day
    }
    
    // 格式化开票时间 (审核时间 okDate)
    let okYear = '', okMonth = '', okDay = ''
    if (judgeInfo.createTime) {
      // 使用 judgeInfo 里的 auditTime 对应的原始时间戳
      const timeStr = judgeInfo.auditTime || ''
      if (timeStr) {
        // 解析格式如 "2025-01-15 10:30:00"
        const match = timeStr.match(/(\d{4})-(\d{2})-(\d{2})/)
        if (match) {
          okYear = parseInt(match[1])
          okMonth = parseInt(match[2])
          okDay = parseInt(match[3])
        }
      }
    }
    
    this.setData({
      previewData: {
        saleCode: judgeInfo.saleCode || '',
        customerName: judgeInfo.customerName,
        address: judgeInfo.address || '',
        phone: judgeInfo.phone || '',
        aboutOrder: judgeInfo.aboutOrder || '',
        products: judgeInfo.products || [],
        isLicens: judgeInfo.isLicens || false,
        isCheck: judgeInfo.isCheck || false,
        createYear,
        createMonth,
        createDay,
        okYear,
        okMonth,
        okDay
      },
      showPreview: true
    })
  },

  // 关闭预览
  closePreview() {
    this.setData({ showPreview: false })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除倒计时定时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
